package com.feihong.yw189.bluetooth.startreadcard;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import com.feihong.yw189.bluetooth.bleutils.BleGlobUtils;
import com.feihong.yw189.bluetooth.bleutils.BleHttpUtils;
import com.feihong.yw189.bluetooth.listener.InitHodListener;
import com.feihong.yw189.bluetooth.listener.UpLoadListener;
import com.feihong.yw189.bluetooth.utils.util.Busi_Idcard_device;
import com.feihong.yw189.bluetooth.utils.util.CallBack;
import com.feihong.yw189.bluetooth.utils.util.ConstantsValue;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;
import com.guoguang.jni.JniCall;
import com.sunnada.SYDReader.IdentityCardS;
import com.sunnada.bluetooth.SYDBlueReaderHelper;

import slam.ajni.MyBitmap;


/**
 * 恒鸿达读卡
 * 2017/8/24
 * 张鹏
 */
public class HengHongDaConnectUtils {
    private BluetoothDevice remoteDevice;
    private String bleAddress;
    private BluetoothAdapter ba;
    private Context context;
    private Activity mActivity;
    private String name, sex, nation, id_num, address, sign_office, to, from, born;
    private String birth_year, birth_month, birth_day, sign_data, photoHeard;
    public SYDBlueReaderHelper mIdUtil = null;
    private Bitmap photo;
    private String bluetoothName = "";
    private BleHttpUtils bleHttpUtils;
    private Boolean mFlag = false;
    // 注册成功失败监听
    private UpLoadListener mOnUpLoadListener;
    public Busi_Idcard_device midHandler = null;
    private IdentityCardS minfo;
    private String bleName;
    public HengHongDaConnectUtils(Context context, BluetoothAdapter ba, BluetoothDevice remoteDevice,
                                  String bleName,  String bleAddress, final String bluetoothName,
                                  Boolean flag, final UpLoadListener mOnUpLoadListener) {
        this.context = context;
        this.mActivity = (Activity) context;
        this.ba = ba;
        this.remoteDevice = remoteDevice;
        this.bleName = bleName;
        this.bleAddress = bleAddress;
        this.mFlag = flag;
        this.bluetoothName = bluetoothName;
        this.mOnUpLoadListener = mOnUpLoadListener;
    }

    public void connect() {

        bleHttpUtils = new BleHttpUtils(context, bluetoothName, mFlag, new UpLoadListener() {
            @Override
            public void onSucUpLoad(String bluetoohName, String address, String sex, String id_num,
                                    String nation, String sign_office, String name, String sign_data,
                                    String birth_year, String birth_month, String birth_day,
                                    Bitmap photo, String filePhoto, String idPath, String to,
                                    String from, String born, String photoHeard) {
                mOnUpLoadListener.onSucUpLoad(bluetoothName, address, sex, id_num, nation,
                        sign_office, name, sign_data, birth_year, birth_month, birth_day,
                        photo, filePhoto, idPath, to,
                        from, born, photoHeard);
                // 读卡成功需要断开连接
                stopConnect();
            }

            @Override
            public void onErrUpLoad(String err) {
                mOnUpLoadListener.onErrUpLoad(err);
                // 读卡失败需要断开连接
                stopConnect();
            }
        });
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 恒鸿达所需
                midHandler = new Busi_Idcard_device(context, new InitHodListener() {
                    @Override
                    public void initHod(String err) {
                        mOnUpLoadListener.onErrUpLoad(err);
                    }
                });
                mIdUtil = new SYDBlueReaderHelper(midHandler.BmHanddler, context);
                minfo = new IdentityCardS();

                if (remoteDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mOnUpLoadListener.onErrUpLoad("该设备未配对");
                } else {
                    // 正在读卡
                    procbluetoothScan();
                }
            }
        });
    }


    /**
     * 断开连接
     */
    public void stopConnect() {
        try {
            if (mIdUtil != null) {
                mIdUtil.close();
            }
            Log.e("项目异常恒鸿达", "------恒鸿达断开连接------");
        } catch (Exception e) {
            Log.e("项目异常", "------断开连接异常------" + e.toString());
            mOnUpLoadListener.onErrUpLoad("");
            e.printStackTrace();
        }


    }

    // 恒鸿达处理阅读器识别
    public void procScan() {
        // 身份证识别
        new Thread() {
            public void run() {
                try {
                    if (mIdUtil.registerBlueCard(bleAddress)) {
                        mIdUtil.readCard();
                    } else {
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mOnUpLoadListener.onErrUpLoad("设备注册失败");
                                midHandler.BmHanddler.sendEmptyMessage(midHandler.MSG_CHECK_ID_FAIL);
                            }
                        });
                    }
                } catch (final Exception e) {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mOnUpLoadListener.onErrUpLoad("读取数据失败:" + e.toString());
                            midHandler.BmHanddler.sendEmptyMessage(midHandler.MSG_CHECK_ID_FAIL);
                        }
                    });
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 恒鸿达开始读身份证
     */
    private void procbluetoothScan() {
        midHandler.setIdCardCallback(new CallBack() {
            public void HandleResult(IdentityCardS idCardArray, byte[] image, short[] imagelen) {
                minfo = idCardArray;
                if (idCardArray != null) {
                    /**
                     * 图片保存位置
                     * **/
                    if (minfo.avatar != null) {
                        //解码头像
                        int res = -1;
                        byte[] szImageData = new byte[306 * 126];
                        try {
                            res = JniCall.Huaxu_Wlt2Bmp(minfo.avatar, szImageData, 708);
                            Log.e("项目异常", "------JniCall------" + res);
                            if (res != 1) {
                                szImageData = null;
                            }
                        } catch (Exception e) {
                            mOnUpLoadListener.onErrUpLoad("读取数据失败:" + e.toString());
                            szImageData = null;
                            e.printStackTrace();
                        }
                        if (szImageData != null) {
                            /**身份证信息加载进来 */
                            photo = MyBitmap.createMyBitmap(szImageData, 102, 126);
                            //头像
                            photoHeard = BleGlobUtils.replaceBlank(
                                    BleGlobUtils.bitmapToBase64(photo));
                            //名字
                            name = minfo.name.toString().trim();
                            //性别
                            sex = minfo.sex;
                            //民族
                            nation = minfo.ethnicity;
                            //出生年月日
                            born = minfo.birth.substring(0, 4) + minfo.birth.substring(4, 6)
                                    + minfo.birth.substring(6, 8);
                            birth_year = minfo.birth.substring(0, 4);
                            birth_month = minfo.birth.substring(4, 6);
                            birth_day = minfo.birth.substring(6, 8);

                            //住址
                            address = minfo.address;
                            //证件号
                            id_num = minfo.cardNo;
                            //签发机关
                            sign_office = minfo.authority;
                            from = minfo.period.substring(0, 4) +
                                    minfo.period.substring(4, 6) +
                                    minfo.period.substring(6, 8);

                            if (minfo.period.contains("长期")) {
                                sign_data = minfo.period.substring(0, 4)
                                        + "." + minfo.period.substring(4, 6) + "." +
                                        minfo.period.substring(6, 8) + "--" +
                                        "长期";
                                to = "长期";
                            } else {
                                //有效日期  to ----from
                                to = minfo.period.substring(9, 13) +
                                        minfo.period.substring(13, 15) +
                                        minfo.period.substring(15, 17);
                                sign_data = minfo.period.substring(0, 4)
                                        + "." + minfo.period.substring(4, 6) + "." +
                                        minfo.period.substring(6, 8) + "--" +
                                        minfo.period.substring(9, 13) + "."
                                        + minfo.period.substring(13, 15) + "." +
                                        minfo.period.substring(15, 17);
                            }
                            Log.e("项目异常", name + "------1------" + id_num);
                            bleHttpUtils.upLoadSfzPhoto(bleName, bleAddress,address, photoHeard, sex, id_num, nation,
                                    sign_office, to, name, from, born, sign_data, birth_year,
                                    birth_month, birth_day, photo);
                        } else {
                            mOnUpLoadListener.onErrUpLoad("读取数据失败,szImageData为空");
                        }
                    } else {
                        mOnUpLoadListener.onErrUpLoad("读取数据失败,minfo.avatar为空");
                    }
                } else {
                    mOnUpLoadListener.onErrUpLoad("读取数据失败,idCardArray为空");
                }
            }
        });

        String hhdIp = PrefUtils.getString(mActivity, ConstantsValue.HHDserverIp, "60.12.230.254");
        String hhdAcc = PrefUtils.getString(mActivity, ConstantsValue.HHDaccount, "V1.0.01");
        String hhdPort = PrefUtils.getString(mActivity, ConstantsValue.HHDport, "23800");
        mIdUtil.setTheServer(hhdIp, Integer.valueOf(hhdPort), hhdIp, Integer.valueOf(hhdPort));
        procScan();
    }
}
